<template>
  <div class="content-box" v-loading="!dataLoaded">
    <div class="content">
      <div class="group">
        <div class="header">
          <el-input readonly v-model="mapName">
            <template #append>
              <el-button :icon="Search" @click="dialogVisible = true" />
            </template>
          </el-input>
        </div>
        <div class="table-box" v-loading="loading">
          <ProTable
            ref="proTable"
            title="门禁点列表"
            rowKey="doorid"
            :columns="columns"
            :request-api="getTableList"
            :data-callback="dataCallback"
            :tool-button="false"
            :select="_select"
            :click-row="_clickRow"
            :all-select-disabled="true"
            :search-col="{ xs: 1, sm: 1, md: 1, lg: 2, xl: 2 }"
            :small="true"
            v-if="zNodes.length"
          >
            <template #tableHeader>
              <el-button type="primary" text :icon="CopyDocument" @click="_copyAccess">复制权限</el-button>
            </template>
            <!-- Expand -->
            <template #expand="scope">
              {{ scope.row }}
            </template>
          </ProTable>
        </div>
      </div>
      <div class="main">
        <div class="table-box" v-loading="loading1">
          <ProTable
            ref="proTable1"
            title="人员列表"
            rowKey="empid"
            :columns="columns1"
            :request-api="getTableList1"
            :data-callback="dataCallback1"
            :tool-button="false"
            :search-col="{ xs: 1, sm: 1, md: 1, lg: 2, xl: 2 }"
            :small="true"
            v-if="columns1.length"
          >
            <template #tableHeader="scope">
              <el-button type="primary" text :icon="CirclePlus" @click="openDialog">增加</el-button>
              <el-button type="danger" text :icon="Delete" @click="_batchDel(scope.selectedListIds)">删除</el-button>
            </template>
            <!-- Expand -->
            <template #expand="scope">
              {{ scope.row }}
            </template>
          </ProTable>
        </div>
      </div>
    </div>
    <TreeDialog
      :zNodes="zNodes"
      :dialogVisible="dialogVisible"
      :handleClose="handleClose"
      :submitCallback="getMapids"
      v-if="zNodes.length"
    />
    <EmployeeDialog
      :doorSn="curDoor.doorsn"
      :dialogVisible="dialogVisible1"
      :handleClose="handleClose"
      :submitCallback="_submitEmp"
      :empcardTypes="empcardTypes"
    />
    <DoorDialog
      :dialogVisible="dialogVisible2"
      :zNodes="zNodes"
      :excludeDoorSn="curDoor.doorsn"
      :handleClose="handleClose"
      :submitCallback="_submitDoor"
      v-if="zNodes.length"
    />
  </div>
</template>
<script setup lang="tsx" name="cardholder">
import { onMounted, ref } from "vue";
import ProTable from "@/components/ProTable/index.vue";
import TreeDialog from "./components/TreeDialog.vue";
import DoorDialog from "./components/DoorDialog.vue";
import EmployeeDialog from "./components/EmployeeDialog.vue";
import { CopyDocument, CirclePlus, Delete } from "@element-plus/icons-vue";
import { Search } from "@element-plus/icons-vue";
import {
  getDoorList,
  getAuthEmployeeList,
  getEmpcardTypes,
  addAccess,
  delAccess,
  copyDoorAccess
} from "@/api/modules/elevatorControl/empower/elevator";

import { getMapTree } from "@/api/modules/common";
import { ElMessage, ElMessageBox } from "element-plus";

const dialogVisible = ref(false);
const dialogVisible1 = ref(false);
const dialogVisible2 = ref(false);
const dataLoaded = ref(false);
const loading = ref(false);
const loading1 = ref(false);
const proTable = ref();
const mapids = ref([]);
const columns1: any = ref([]);
const proTable1 = ref();
const curDoor: any = ref({});
const zNodes: any = ref([]);
const empcardTypes = ref([]);
const mapName = ref("");

const dataCallback = (data: any) => {
  const { records, page } = data;
  loading.value = false;
  return {
    list: records || [],
    total: page.total
  };
};

const dataCallback1 = (data: any) => {
  console.log(data, "data");
  const { records, page } = data;
  loading1.value = false;
  return {
    list: records || [],
    total: page.total
  };
};

const getTableList = (params: any) => {
  let newParams = JSON.parse(JSON.stringify(params));
  loading.value = true;
  return getDoorList({ ...newParams, mapIds: mapids.value, checkOptDoorRight: true, checkArea: true, doorType: 1 });
};

const getTableList1 = (params: any) => {
  let newParams = JSON.parse(JSON.stringify(params));
  loading1.value = true;
  if (!curDoor.value.doorsn) {
    return new Promise(function (resolve) {
      resolve({ data: { page: { total: 0 }, records: [] } });
    });
  } else {
    return getAuthEmployeeList({
      ...newParams,
      doorSn: curDoor.value.doorsn ?? ""
    });
  }
};

const columns: any = [
  { type: "selection", fixed: "left", width: 60 },
  {
    prop: "clause",
    label: "",
    isShow: false,
    search: { el: "input" }
  },
  {
    prop: "doorsn",
    label: "门禁点编码",
    minWidth: 120
  },
  {
    prop: "doorname",
    label: "门禁点描述",
    minWidth: 120
  }
];

/**
 * 多选框选择
 */
const _select = (selection, row) => {
  const selectedList = proTable.value.element.getSelectionRows();
  const isSel = selectedList.some(item => item.doorid === row.doorid);
  const lastSelItem = selection.shift();
  if (selection.length) {
    proTable.value.element.toggleRowSelection(lastSelItem, false);
  }
  curDoor.value = isSel ? row : {};
  proTable1.value.clearSelection();
  proTable1.value.getTableList();
};

/**
 * 单击行
 */
const _clickRow = row => {
  const selectedList = proTable.value.element.getSelectionRows();
  const isSel = selectedList.some(item => item.doorid === row.doorid);
  proTable.value.clearSelection();
  proTable.value.element.toggleRowSelection(row, isSel ? false : true);
  curDoor.value = !isSel ? row : {};
  proTable1.value.clearSelection();
  proTable1.value.getTableList();
};

const _batchDel = async (selectedListIds: string[]) => {
  console.log(selectedListIds);
  if (!selectedListIds.length) {
    ElMessage.error("请选择人员");
    return false;
  }
  ElMessageBox.confirm(`是否删除所选人员?`, "温馨提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
    draggable: true
  }).then(async () => {
    try {
      const res = await delAccess({
        doorSns: [curDoor.value.doorsn],
        empIds: selectedListIds
      });
      const { v1, v2 } = res.data;
      ElMessage.success(`删除成功：${v1},失败：${v2}`);

      proTable1.value.clearSelection();
      proTable1.value.getTableList();
    } catch (error) {
      console.log(error);
    }
  });
};

const _copyAccess = () => {
  if (!curDoor.value.doorsn) {
    ElMessage.error("请选择被复制门禁点");
    return false;
  }
  dialogVisible2.value = true;
};

const _submitDoor = async (ids: string[]) => {
  try {
    const res = await copyDoorAccess({ doorSnSrcList: [curDoor.value.doorsn], doorSnDesList: ids });
    const { v1, v2 } = res.data;
    dialogVisible2.value = false;
    ElMessage.success(`复制成功：${v1},失败：${v2}`);
  } catch (error) {
    console.log(error);
  }
};

const _submitEmp = async (ids: string[]) => {
  try {
    const res = await addAccess({
      doorSns: [curDoor.value.doorsn],
      empIds: ids,
      timeCode: 0
    });
    const { v1, v2 } = res.data;
    dialogVisible1.value = false;
    ElMessage.success(`增加成功：${v1},失败：${v2}`);
    proTable1.value.clearSelection();
    proTable1.value.reset();
  } catch (error) {
    console.log(error);
  }
};

/**
 * 增加人员弹窗
 */
const openDialog = () => {
  if (!curDoor.value?.doorsn) {
    ElMessage.error("请先选择门禁点");
    return false;
  }
  dialogVisible1.value = true;
};

/**
 * 获取mapids
 */
const getMapids = (name, ids) => {
  mapName.value = name;
  mapids.value = ids;
  curDoor.value = {};
  dialogVisible.value = false;
  proTable.value.clearSelection();
  proTable.value.getTableList();
  proTable1.value.clearSelection();
  proTable1.value.reset();
};

/**
 * 关闭弹窗
 */
const handleClose = () => {
  dialogVisible.value = false;
  dialogVisible1.value = false;
  dialogVisible2.value = false;
};

/**
 * 获取酒店选择下拉列表
 */
const getEmpcardTypeData = async () => {
  try {
    const res = await getEmpcardTypes();
    empcardTypes.value = res.data.map(item => {
      return {
        label: item.value,
        value: item.key
      };
    });
    columns1.value = [
      { type: "selection", fixed: "left", width: 60 },
      {
        prop: "cardType",
        label: "类型",
        isShow: false,
        enum: empcardTypes.value,
        search: {
          el: "select"
        }
      },
      {
        prop: "clause",
        label: "姓名",
        isShow: false,
        search: {
          el: "input"
        }
      },
      {
        prop: "empid",
        label: "编码",
        minWidth: 120
      },
      {
        prop: "empname",
        label: "姓名",

        minWidth: 200
      },
      {
        prop: "dptName",
        label: "部门",
        minWidth: 200
      },
      {
        prop: "cardvalid",
        label: "有效期",
        minWidth: 200
      }
    ];
  } catch (error) {
    columns1.value = [
      { type: "selection", fixed: "left", width: 60 },
      {
        prop: "clause",
        label: "姓名",
        isShow: false,
        search: {
          el: "input"
        }
      },
      {
        prop: "empid",
        label: "编码",
        minWidth: 120
      },
      {
        prop: "empname",
        label: "姓名",
        minWidth: 200
      },
      {
        prop: "dptName",
        label: "部门",
        minWidth: 200
      },
      {
        prop: "cardvalid",
        label: "有效期",
        minWidth: 200
      }
    ];
    console.log(error);
  }
};
const getMapData = async () => {
  try {
    const res = await getMapTree({
      mapType: 1
    });
    zNodes.value = res.data;
    if (zNodes.value.length) {
      mapName.value = zNodes.value[0].name;
      mapids.value = getFlatMapData(zNodes.value).map(item => item.id);
    }
  } catch (error) {
    console.log(error);
  }
};

/**
 * 展开树
 */
const getFlatMapData = (list: any) => {
  let newList = JSON.parse(JSON.stringify(list));
  return newList.flatMap((item: any) => [item, ...(item.children ? getFlatMapData(item.children) : [])]);
};

onMounted(async () => {
  Promise.all([getEmpcardTypeData(), getMapData()]).then(() => {
    dataLoaded.value = true;
  });
});
</script>
<style scoped lang="scss">
@import "./index.scss";
</style>
